package com.et114.components.jcaptcha;

import com.octo.captcha.service.CaptchaServiceException;
import com.octo.captcha.service.image.ImageCaptchaService;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import org.apache.commons.lang.StringUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * 
 * @author guanhw
 */
public class ImageCaptchaServlet extends HttpServlet {
	private static final long	serialVersionUID	= 3258417209566116145L;
	private String				captchaServiceName	= "imageCaptchaService";

	public void init ( ServletConfig servletConfig ) throws ServletException {
		if ( StringUtils.isNotBlank( servletConfig.getInitParameter( "captchaServiceName" ) ) ) {
			captchaServiceName = servletConfig	.getInitParameter( "captchaServiceName" );
		}

		super.init( servletConfig );
	}

	protected void doGet ( HttpServletRequest httpServletRequest ,
			HttpServletResponse httpServletResponse ) throws ServletException ,
			IOException {

		byte [ ] captchaChallengeAsJpeg = null;
		// the output stream to render the captcha image as jpeg into
		ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
		try {
			ApplicationContext ctx = WebApplicationContextUtils
					.getRequiredWebApplicationContext( getServletContext() );
			Object bean = ctx.getBean( captchaServiceName );
			ImageCaptchaService imageCaptchaService = ( ImageCaptchaService ) bean;
			String captchaId = httpServletRequest.getSession().getId();
			BufferedImage challenge = imageCaptchaService.getImageChallengeForID( captchaId, httpServletRequest	.getLocale() );
			JPEGImageEncoder jpegEncoder = JPEGCodec.createJPEGEncoder( jpegOutputStream );
			jpegEncoder.encode( challenge );
		} catch ( IllegalArgumentException e ) {
			httpServletResponse.sendError( HttpServletResponse.SC_NOT_FOUND );
			return;
		} catch ( CaptchaServiceException e ) {
			httpServletResponse.sendError( HttpServletResponse.SC_INTERNAL_SERVER_ERROR );
			return;
		}
		captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
		httpServletResponse.setHeader( "Cache-Control", "no-store" );
		httpServletResponse.setHeader( "Pragma", "no-cache" );
		httpServletResponse.setDateHeader( "Expires", 0 );
		httpServletResponse.setContentType( "image/jpeg" );
		ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
		responseOutputStream.write( captchaChallengeAsJpeg );
		responseOutputStream.flush();
		responseOutputStream.close();
	}
}
